package com.thedeveloperworldisyours.fullrecycleview.single;

import com.thedeveloperworldisyours.fullrecycleview.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

/**
 * Created by javierg on 02/02/2017.
 */

public class SingleRecyclerViewAdapter extends BaseItemProvider {

    private List<String> mData;
    private SingleClickListener sClickListener;
    private int sSelected = -1;
    private LayoutScatter scatter;

    public SingleRecyclerViewAdapter(LayoutScatter scatter,List<String> mData) {
        this.scatter = scatter;
        this.mData = mData;
    }

    class DataObjectHolder implements Component.ClickedListener {
        Text mTextView;
        RadioButton mRadioButton;
        int position;

        public DataObjectHolder(Component itemView, int position) {
            this.position = position;
            this.mTextView = (Text) itemView.findComponentById(ResourceTable.Id_single_list_item_text);
            this.mRadioButton = (RadioButton) itemView.findComponentById(ResourceTable.Id_single_list_item_check_button);
            this.mRadioButton.setButtonElement(null);
            this.mRadioButton.setEnabled(false);
            itemView.setClickedListener(this);
        }

        @Override
        public void onClick(Component view) {
            sSelected = position;
            sClickListener.onItemClickListener(position, view);
        }

        public void setPosition(int position) {
            this.position = position;
        }
    }

    public void selectedItem() {
        notifyDataChanged();
    }

    void setOnItemClickListener(SingleClickListener clickListener) {
        sClickListener = clickListener;
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        DataObjectHolder dataObjectHolder;
        if (component == null) {
            Context context = componentContainer.getContext();
            component = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_single_list_item, componentContainer, false);
            dataObjectHolder = new DataObjectHolder(component, position);
            component.setTag(dataObjectHolder);
        } else {
            dataObjectHolder = (DataObjectHolder) component.getTag();
        }
        dataObjectHolder.setPosition(position);
        dataObjectHolder.mTextView.setText(mData.get(position));
        dataObjectHolder.mRadioButton.setChecked(sSelected == position);
        return component;
    }


    @Override
    public int getCount() {
        return mData.size();
    }

    interface SingleClickListener {
        void onItemClickListener(int position, Component view);
    }

}
